var serviceTarget ="http://api.lobatu.com"
var webTarget = 'http://m.lobatu.com/index.html'
var domain = 'http://m.lobatu.com'

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

//格式化日期,
function formatDate(date,format){
	var paddNum = function(num){
	  num += "";
	  return num.replace(/^(\d)$/,"0$1");
	}
	//指定格式字符
	var cfg = {
	   yyyy : date.getFullYear() //年 : 4位
	  ,yy : date.getFullYear().toString().substring(2)//年 : 2位
	  ,M  : date.getMonth() + 1  //月 : 如果1位的时候不补0
	  ,MM : paddNum(date.getMonth() + 1) //月 : 如果1位的时候补0
	  ,d  : date.getDate()   //日 : 如果1位的时候不补0
	  ,dd : paddNum(date.getDate())//日 : 如果1位的时候补0
	  ,hh : date.getHours()  //时
	  ,mm : date.getMinutes() //分
	  ,ss : date.getSeconds() //秒
	}
	format || (format = "yyyy-MM-dd hh:mm:ss");
	return format.replace(/([a-z])(\1)*/ig,function(m){return cfg[m];});
} 

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

function login() {
	// #ifdef H5
	
    var  lastUrl = window.location.href
	uni.setStorageSync('lastUrl', lastUrl); //记录下最后url 返回时，由首页做中转
	location.href = serviceTarget+'/api/wx_authorize.do?callback='+webTarget
	

	// #endif
};

// 接口请求Post函数
function fetchPost(requestUrl, data, success, err,requestLogin) {
	var value = {}
	if(uni.getStorageSync('UserInfo')) {
		value =JSON.parse(uni.getStorageSync('UserInfo')); 
	}
	
	//每次请求先判断token，没有token都去登陆
	if(requestLogin!==false){
		if(!value.token && requestUrl.indexOf("wx_login")<0){
			login();
			return;
		}
	}
	
	uni.request({
		url: serviceTarget + requestUrl,
		dataType: 'json',
		header: {
			'content-type' :'application/x-www-form-urlencoded',
			'token': value.token,
			'X-Requested-With':'XMLHttpRequest',
			},
		method: 'POST',
		data: data,
		success: (res) => {
			//这里需要增加判断，如果返回token 已经失效，必须要重新去登录， token失效的编码，随便穿一个错误的token就知道了
			//{login_status=300, code=200001, message=当前用户没有登录！}
			
			
			
			if(res.data.code==200001){
				uni.removeStorageSync("UserInfo");
			    login();	
			}else{
					success(res.data);
			}
		
		},
		fail: (err) => {
			if(err.code==200001){
				uni.removeStorageSync("UserInfo");
			    login();	
			}
			// console.log('request fail', err);
			// uni.showModal({
			// 	content: err.errMsg,
			// 	showCancel: false
			// });
		},
		complete: () => {
			this.loading = false;
		}
	});
};

// 接口请求Get函数
//修改时间，接口访问增加是否需要登录 默认为必须登录
function fetchGet(requestUrl, data, success, err,requestLogin) {
	var value = {}
	if(uni.getStorageSync('UserInfo')) {
		value =JSON.parse(uni.getStorageSync('UserInfo')); 
	}
	//每次请求先判断token，没有token都去登陆
	if(requestLogin!=false){
		if(!value.token){
			login();
			return;
		}
	}
	
	uni.request({
		url: serviceTarget + requestUrl,
		dataType: 'json',
		method: 'GET',
		header: {'token': value.token,'X-Requested-With':'XMLHttpRequest'},
		data: data,
		success: (res) => {
			uni.hideLoading();
			if(res.data.code==200001){
				uni.removeStorageSync("UserInfo");
			    login();	
			}else{
				success(res.data);
			}
			
		},
		fail: (err) => {
			uni.hideLoading();
			if(err.code==200001){
				uni.removeStorageSync("UserInfo");
			    this.login();	
			}
			// console.log('request fail', err);
			// uni.showModal({
			// 	content: err.errMsg,
			// 	showCancel: false
			// });
		},
		complete: () => {
			this.loading = false;
		}
	});
};

function IdCardUtils(UUserCard, num) {
	if (num == 1) {
		//获取出生日期
		birth = UUserCard.substring(6, 10) + "-" + UUserCard.substring(10, 12) + "-" + UUserCard.substring(12, 14);
		return birth;
	}
	if (num == 2) {
		//获取性别
		if (parseInt(UUserCard.substr(16, 1)) % 2 == 1) {
			//男
			return "男";
		} else {
			//女
			return "女";
		}
	}
	if (num == 3) {
		//获取年龄
		var myDate = new Date();
		var month = myDate.getMonth() + 1;
		var day = myDate.getDate();
		var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
		if (UUserCard.substring(10, 12) < month || UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) <= day) {
			age++;
		}
		return age;
	}
}
	//校验身份证号
function CalculateIdCard(id) {
	var that=this;
	var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
	if (reg.test(id) === false) {
		uni.showModal({
			content: '身份证不合法',
			showCancel: false
		});
		return false;
	} else {
		return true;
	}
	
}
function checkPhone(phone){ 
    if(!(/^1[23456789]\d{9}$/.test(phone))){ 
        return false; 
    }else{
		return true;
	}
}


module.exports = {
	checkPhone:checkPhone,
	IdCardUtils:IdCardUtils,
	CalculateIdCard:CalculateIdCard,
	formatDate:formatDate,
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	fetchPost: fetchPost,
	fetchGet: fetchGet,
	serviceTarget,
	webTarget,
	domain
}
